<?php

namespace app\data\service;

use app\admin\service\FeiShuService;
use app\admin\service\WxWorkService;
use think\admin\Service;
use think\db\exception\DbException;
use think\facade\Log;

/**
 * 采集消息
 * Class MessageParse
 * @package app\data\service
 */
class MessageParseService extends Service
{
    /**
     * 解析文本消息
     * @param $content
     * @param $mentions
     * @return array|mixed|string|string[]
     */
    public function translationText($content, $mentions = null)
    {
        $content = json_decode($content, true);
        $text = $content['text'] ?? '';

        if (!empty($mentions)) {
            $mentions = json_decode($mentions, true);
            foreach ($mentions as $mention) {
                $text = str_replace($mention['key'], $mention['name'], $text);
            }
        }

        return $text;
    }

    public function carParse($text, $message)
    {
        // 调用腾讯地图api
        $message = $this->matchTencentParse($message);

        $message['wechat_message'] = $text;

        // 1、车牌号码为唯一条件，根据是否完工为判断准则，若完工则新增数据，若未完工，则进行数据覆盖（覆盖只司机姓名、手机号、城市、车型这几个；）；
        // 2、信息采集数据周期查询为2个月，2个月内的数据判断以上条件，2个月前的数据不予判断，直接新增。
        $existRecord = RecordService::instance()->isExist($message['phone'], $message['plate_number']);

        // 已经存在未完工的记录且地区不一样的数据进行覆盖
        if ($existRecord && in_array($existRecord['paint_status'], [0, -1])) {

            if (!empty($message['phone'])) {
                $updateMessage['phone'] = $message['phone'];
            }
            if (!empty($message['username'])) {
                $updateMessage['username'] = $message['username'];
            }
            if (!empty($message['province'])) {
                $updateMessage['province'] = $message['province'];
            }
            if (!empty($message['city'])) {
                $updateMessage['city'] = $message['city'];
            }
            if (!empty($message['province_owner'])) {
                $updateMessage['province_owner'] = $message['province_owner'];
            }
            if (!empty($message['city_owner'])) {
                $updateMessage['city_owner'] = $message['city_owner'];
            }
            if (!empty($message['car_vehicle_type'])) {
                $updateMessage['car_vehicle_type'] = $message['car_vehicle_type'];
            }
            if (!empty($message['car_color'])) {
                $updateMessage['car_color'] = $message['car_color'];
            }
            if (!empty($message['car_vehicle_type_id'])) {
                $updateMessage['car_vehicle_type_id'] = $message['car_vehicle_type_id'];
            }

            if (!empty($updateMessage)) {
                $this->app->db->name('data_record')->where('id', $existRecord['id'])->update($updateMessage);
            }

            unset($updateMessage);
        }

        if (!$existRecord) {

            // 派单
            $this->dispatchOrder($message);

            // 检查是否有未同步手机号的车辆
            $carInfo = $this->app->db->name('car_infos')->where('plate_number', $message['plate_number'])->where('phone', '')->findOrEmpty();
            if ($carInfo) {
                $this->app->db->name('car_infos')->where('plate_number', $message['plate_number'])->update(['is_sync' => 0, 'phone' => $message['phone']]);
            }
        }
    }

    public function manualEntry($text, $message)
    {
        // 手动录入
        unset($message['has_uuid_city']);

        // 调用腾讯地图api
        $message = $this->matchTencentParse($message);

        $message['wechat_message'] = $text;
        $existRecord = RecordService::instance()->isExist($message['phone'], $message['plate_number']);

        if (!$existRecord) {
            $message['id'] = $this->app->db->name('data_record')->insertGetId($message);
        } else {
            // 已完成就全部不修改
            // 未完成就不能修改对接日期，首次和最近邀约情况和日期
            if ($existRecord['paint_status'] != 1) {
                if (empty($message['uuid_city'])) {
                    unset($message['uuid_city']);
                }
                unset($message['time_docking']);
                unset($message['time_invites']);
                unset($message['time_invite']);
                unset($message['invite_remarks']);
                unset($message['invite_remark']);

                $this->app->db->name('data_record')->where('id', $existRecord['id'])->update($message);
            }
        }
    }

    public function completeInfo($message)
    {
        RecordService::instance()->saveCompleteData($message);
    }

    public function inviteInfo($text)
    {
        // 保存邀约情况
        [$record, $inviteRemark] = StringParse::instance()->inviteInfo($text);
        if (!$record) {
            Log::error('邀约信息匹配失败 ' . $text);
        } else {
            if (RecordService::instance()->saveInviteRemark($record, $inviteRemark)) {
                // 发送企业微信消息-对接人员工
                $openId = $this->app->db->name('work_user')->where('id', $record['uuid_docking'])->value('open_id');
                FeiShuService::instance()->sendMessageTextByUserid($openId, "{$record['plate_number']};$inviteRemark");
            }
        }
    }

    public function matchTencentParse($message)
    {
        $tencentParse = StringParse::instance()->tencentParse($message['province']);
        if (empty($tencentParse['province'])) {
            $tencentParse = StringParse::instance()->tencentParse($message['city']);
        }
        $message['province'] = $tencentParse['province'] ?? '';
        $message['city'] = $tencentParse['city'] ?? '';
        $message['area'] = $tencentParse['area'] ?? '';

        $relation = $this->app->db->name('data_city_relation')->where('from_province', $message['province'])->where('from_city', $message['city'])->findOrEmpty();
        if (!empty($relation)) {
            $message['province_owner'] = $relation['to_province'] ?? '';
            $message['city_owner'] = $relation['to_city'] ?? '';
        } else {
            $message['province_owner'] = $tencentParse['province'] ?? '';
            $message['city_owner'] = $tencentParse['city'] ?? '';
        }


        return $message;
    }

    /**
     * 派单
     * @param $message
     * @return void
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function dispatchOrder($message, $existRecord = null)
    {
        [$message['city_relation_id'], $toProvince, $toCity] = CityUserRelationService::instance()->mathCityRelationId($message['province'], $message['city']);

        // 匹配数据返回对接人员工ID
        $message['uuid_docking'] = CityUserRelationService::instance()->distributeDockingUuid($message['city_relation_id'], $message['province'], $message['city']);
        $message['uuid_city'] = CityUserRelationService::instance()->distributeCityUuid($message['city_relation_id']);
        if (empty($message['uuid_city'])) {
            $message['uuid_city'] = $message['uuid_docking'];
        }

        if ($existRecord) {
            $this->app->db->name('data_record')->where('id', $existRecord['id'])->update($message);
            $message['id'] = $existRecord['id'];
        } else {
            $message['time_docking'] = date('Y-m-d H:i:s');
            $message['id'] = $this->app->db->name('data_record')->insertGetId($message);
        }


        // 发送企业微信消息-对接人员工
        $openId = $this->app->db->name('work_user')->where('id', $message['uuid_docking'])->value('open_id');
        if (!empty($openId)) {
            $messageText = RecordService::instance()->toForwardText($message, 'docking');
            FeiShuService::instance()->sendMessageTextByUserid($openId, $messageText);
        } else {
            Log::error('扫描微信聊天记录匹配员工失败1 ' . json_encode($message));
        }

        // 发送企业微信消息-城市负责人员工
        if (!empty($message['uuid_city'])) {
            $openId = $this->app->db->name('work_user')->where('id', $message['uuid_city'])->value('open_id');
            if (!empty($openId)) {
                $messageText = RecordService::instance()->toForwardText($message, 'city_owner');
                FeiShuService::instance()->sendMessageTextByUserid($openId, $messageText);
            } else {
                Log::error('扫描微信聊天记录匹配员工失败2 ' . json_encode($message));
            }
        }
    }
}